package com.cn.jani.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.jani.pojo.Inquiry;
import com.cn.jani.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource  
    private UserService userService;  
	
	private static List<String> names = new ArrayList<String>(){
		{
			add("q1");
			add("q20");
			add("q21");
			add("q22");
			add("q30");
			add("q31");
			add("q40");
			add("q401");
			add("q41");
			add("q411");
			add("q42");
			add("q421");
			add("q43");
			add("q431");
			add("q44");
			add("q441");
			add("q45");
			add("q50");
			add("q501");
			add("q51");
			add("q511");
			add("q52");
			add("q521");
			add("q60");
		}
	};
      
    @RequestMapping("/showUser")  
    public String toIndex(HttpServletRequest request,Model model){  
    	String isForm = request.getParameter("isForm");
    	Inquiry inquiry = new Inquiry();
    	if("1".equals(isForm)){
			String userName = request.getParameter("userName");
    		try {
            	StringBuffer buffer = new StringBuffer();
            	for(String str : names){
            		String temp = request.getParameter(str);
        			buffer.append(str);
        			buffer.append(":");
        			buffer.append(temp);
        			buffer.append("#*");
            	}
            	String remoteAddr=request.getRemoteAddr();
            	inquiry.setContent(buffer.toString());
            	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	inquiry.setSubmitdate(sd.format(new Date()));
            	inquiry.setUserclientno(remoteAddr);
            	inquiry.setUsername(userName);
            	userService.addInquiry(inquiry);
            	System.out.println(userName + " submit success!");
    		} catch (Exception e) {
            	inquiry.setUsername("Sorry, You submit failed. Try again please! And contact us. ");
            	System.out.println(userName + " submit failed!");
    		}
    	} else {
        	inquiry.setUsername("Do not sumit again!");
        	System.out.println("Someone submit again!");
    	}
        model.addAttribute("inquiry", inquiry); 
        return "showUser";  
    }  
}
